import JSZip from "jszip";
export const LANGUAGES = ['en', 'zh_CN', 'zh_TW'];
export namespace ComUtils {
    export function queryToString(query: any) {
        if (!query) {
            return ''
        }
        if (typeof query !== 'object') {
            return ''
        }
        return Object.keys(query).map(key => {
            if (query[key] === null || query[key] === '' || query[key] === undefined || query[key] === 'undefined') {
                return ''
            }
            if (typeof query[key] === 'object' && query[key]?.length) {
                return `${key}=${JSON.stringify(query[key])}`
            }
            return `${key}=${query[key]}`
        }).filter(item => item.trim() !== '').join('&')
    }
    export function getResourceUrl(url: string) {
        if (!chrome.runtime || !chrome.runtime.getURL) {
            return '/settings' + url
        }
        return chrome.runtime?.getURL(url);
    }

    /**
   * 给当前激活窗口发送信息
   * @param {ChromeMessage} message
   */
    export function sendMessageForTabs(message: ChromeMessage) {
        chrome?.tabs?.query({ active: true, currentWindow: true }, (tabs) => {
            tabs.forEach((tab) => {
                if (tab.id) {
                    chrome.tabs.sendMessage(tab.id, message).catch(console.log)
                }
            })
        })
    }

    export function callChromeMethod<T>(method: string, arg: any, timeout = 10 * 1000): Promise<T> {
        return new Promise((resolve, reject) => {
            if (!chrome.runtime || !chrome.runtime.sendMessage) {
                reject('chrome: runtime not found')
            }
            const timer = setTimeout(() => {
                reject('chrome: timeout')
            }, timeout)
            chrome.runtime.sendMessage({ type: method, data: arg }, (result: ChromeResponse) => {
                clearTimeout(timer)
                if (!result) {
                    reject('chrome: unknown error,method:' + method)
                }
                if (result?.state) {
                    resolve(result?.data)
                } else {
                    reject(result?.message)
                }

            })
        })
    }

    export function tr(txt: string) {
        if (!chrome.i18n) {
            return txt
        }
        const str = chrome.i18n.getMessage(txt);
        return str||txt
    }

    export async function downloadAll(ar: any[], onProgress?: (progress: number) => void) {
        if (!ar.length) {
            onProgress?.(1)
            return
        }
        const zip = new JSZip();
        for (let i = 0; i < ar.length; i++) {
            try {
                const res = ar[i];
                const data = await fetch(res.url).then(res => res.blob())
                zip.file(res.name, data)
                onProgress?.(i / ar.length)
            } catch (error) {
                console.log(error)
            }
        }
        const blob = await zip.generateAsync({ type: "blob" })
        const file = new File([blob], "resources.zip", { type: "application/zip" })
        const url = URL.createObjectURL(file)
        onProgress?.(1)
        chrome.downloads.download({
            url,
            filename: "resources.zip",
            saveAs: true
        });
    }

    export function waitTime(time: number = 1000) {
        return new Promise(resolve => {
            setTimeout(resolve, time)
        })
    }

    export function formatDate(time: number, isUtc = false, onlyDate = false) {
        if (!time) {
            return '---- -- --:--:--';
        }
        if (String(time).length < 10) {
            return String(time)
        }
        const date = new Date(String(time).length == 10 ? time * 1000 : time);
        let y = date.getFullYear();
        let m = date.getMonth() + 1;
        let d = date.getDate();
        let h = date.getHours();
        let i = date.getMinutes();
        let s = date.getSeconds();
        if (isUtc) {
            y = date.getUTCFullYear();
            m = date.getUTCMonth() + 1;
            d = date.getUTCDate();
            h = date.getUTCHours();
            i = date.getUTCMinutes();
            s = date.getUTCSeconds();
        }
        if (onlyDate) {
            return `${y}-${m > 9 ? m : ('0' + m)}-${d > 9 ? d : ('0' + d)}`
        }
        return `${y}-${m > 9 ? m : ('0' + m)}-${d > 9 ? d : ('0' + d)} ${h > 9 ? h : ('0' + h)}:${i > 9 ? i : ('0' + i)}:${s > 9 ? s : ('0' + s)}`;
    }

    export function formatBytes(bytes: number) {
        if (!bytes) {
            return '0B'
        }
        if (bytes < 1024) {
            return bytes + "B";
        } else if (bytes < 1048576) {
            return (bytes / 1024).toFixed(2) + "KB";
        } else {
            return (bytes / 1048576).toFixed(2) + "MB";
        }
    }

    export function downloadFile(url: string, name: string) {
        if (chrome.downloads) {
            chrome.downloads.download({ url, saveAs: true, filename: name });
        } else {
            const a = document.createElement('a');
            a.href = url;
            a.download = name;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.remove();
        }
    }

    export async function fetchWithTimeout(url: string, options?: RequestInit, timeout = 5000) {
        const controller = new AbortController();
        const id = setTimeout(() => controller.abort(), timeout);
        const res = await fetch(url, {
            ...options,
            signal: controller.signal
        });
        clearTimeout(id)
        return res
    }

    export async function getActiveTable() {
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
        for (const tab of tabs) {
            if (tab.id) {
                return tab.id
            }
        }
    }
}